package com.alander.nexusgo.user.service.impl;

import cn.hutool.json.JSONUtil;
import com.alander.nexusgo.common.model.dto.CheckinDTO;
import com.alander.nexusgo.common.model.vo.CheckinVO;
import com.alander.nexusgo.framework.file.starter.service.FileUploadService;
import com.alander.nexusgo.user.mapper.UserCheckinsMapper;
import com.alander.nexusgo.user.model.entity.UserCheckins;
import com.alander.nexusgo.user.service.UserCheckinsService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.LambdaUpdateWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
* @author alander
*/
@Slf4j
@Service
@RequiredArgsConstructor
public class UserCheckinsServiceImpl extends ServiceImpl<UserCheckinsMapper, UserCheckins>
    implements UserCheckinsService{

    private final FileUploadService fileUploadService;

    private static final String filePath = "checkins/";

    @Override
    public CheckinVO checkin(CheckinDTO checkinDTO) {
        try {
            List<String> photos = null;
            if(checkinDTO.getPhotos() != null){
                photos = fileUploadService.uploadFiles(checkinDTO.getPhotos(),filePath);
            }
            UserCheckins userCheckins = new UserCheckins();
            BeanUtils.copyProperties(checkinDTO, userCheckins);

            // 处理JSON字段
            if (photos != null) {
                userCheckins.setPhotos(JSONUtil.toJsonStr(photos));
            }
            if (checkinDTO.getTags() != null) {
                userCheckins.setTags(JSONUtil.toJsonStr(checkinDTO.getTags()));
            }

            // 设置打卡时间和日期
            Date now = new Date();
            userCheckins.setCheckinTime(LocalDateTime.now());

            // 保存到数据库
            this.save(userCheckins);

            // 转换为VO并返回
            return convertToVO(userCheckins);
        } catch (Exception e) {
            log.error("用户打卡失败: ", e);
            throw new RuntimeException("打卡失败: " + e.getMessage());
        }
    }

    @Override
    public List<CheckinVO> listUserCheckins(Long userId) {
        LambdaQueryWrapper<UserCheckins> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(UserCheckins::getUserId, userId)
                   .orderByDesc(UserCheckins::getCheckinTime);

        List<UserCheckins> checkinsList = this.list(queryWrapper);

        return checkinsList.stream()
                .map(this::convertToVO)
                .collect(Collectors.toList());
    }

    @Override
    public CheckinVO getCheckinDetail(Long checkinId) {
        UserCheckins userCheckins = this.getById(checkinId);
        if (userCheckins == null) {
            throw new RuntimeException("打卡记录不存在");
        }

        return convertToVO(userCheckins);
    }

    @Override
    public CheckinVO updateCheckin(Long checkinId, CheckinDTO checkinDTO) {
        UserCheckins userCheckins = this.getById(checkinId);
        if (userCheckins == null) {
            throw new RuntimeException("打卡记录不存在");
        }

        // 更新属性
        BeanUtils.copyProperties(checkinDTO, userCheckins, "id", "userId", "checkinTime", "checkinDate");

        // 处理JSON字段
        if (checkinDTO.getPhotos() != null) {
            userCheckins.setPhotos(JSONUtil.toJsonStr(checkinDTO.getPhotos()));
        }
        if (checkinDTO.getTags() != null) {
            userCheckins.setTags(JSONUtil.toJsonStr(checkinDTO.getTags()));
        }

        this.updateById(userCheckins);

        return convertToVO(userCheckins);
    }

    @Override
    public boolean deleteCheckin(Long checkinId) {
        LambdaUpdateWrapper<UserCheckins> updateWrapper = new LambdaUpdateWrapper<>();
        updateWrapper.eq(UserCheckins::getId, checkinId)
                .set(UserCheckins::getDelFlag, "1");
        return this.update(updateWrapper);
    }

    /**
     * 将 UserCheckins 实体转换为 CheckinVO
     * @param userCheckins UserCheckins 实体
     */
    private CheckinVO convertToVO(UserCheckins userCheckins) {
        CheckinVO checkinVO = new CheckinVO();
        BeanUtils.copyProperties(userCheckins, checkinVO);

        // 处理JSON字段
        if (userCheckins.getPhotos() != null) {
            try {
                List<String> photos = JSONUtil.toList(JSONUtil.parseArray(userCheckins.getPhotos().toString()), String.class);
                checkinVO.setPhotos(photos);
            } catch (Exception e) {
                log.warn("解析照片URL失败: ", e);
            }
        }

        if (userCheckins.getTags() != null) {
            try {
                List<String> tags = JSONUtil.toList(JSONUtil.parseArray(userCheckins.getTags().toString()), String.class);
                checkinVO.setTags(tags);
            } catch (Exception e) {
                log.warn("解析标签失败: ", e);
            }
        }

        return checkinVO;
    }
}
